<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | Qrcode管理
// +----------------------------------------------------------------------
namespace app\qrcode\controller;
use think\Db;
use app\common\controller\Adminbase;
use Endroid\QrCode\Writer\PngWriter;
use Endroid\QrCode\QrCode as EnQrcode;
use jianyan\excel\Excel;

class Qrcode extends Adminbase
{
    protected function initialize()
    {
        parent::initialize();
        $this->modelClass = Db::name('qrcode');
    }

    /**
     * qrcode列表
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $get = $this->request->get('', null, null);
            list($page, $limit, $where) = $this->buildTableParames();
            $total = Db::name('qrcode')->where($where)->count();
            $list = Db::name('qrcode')
                ->where($where)
                ->field('*,FROM_UNIXTIME(create_time,"%Y-%m-%d %H:%i:%s") as create_time')
                ->page($page, $limit)->order('create_time desc,id desc')->select();
            foreach ($list as $k => $v) {
                $_list[]         = $v;
            }
            $result = array("code" => 0, "count" => $total, "data" => $_list);
            return json($result);
        }
        return $this->fetch();
    }

    /**
     * add列表
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $code = $this->getNonceStr();
            $url = 'http://www.yuejiapower.com/product/query?code='.$code;
            $qrCode = EnQrcode::create($url)->setSize(300)->setMargin(10);
            $writer = new PngWriter();
            $result = $writer->write($qrCode);
            $result->saveToFile('uploads/qrcode/'.$code.'.png');
            $res = Db::name('qrcode')->insert(['code'=>$code, 'qrcode'=>'/uploads/qrcode/'.$code.'.png', 'url'=>$url, 'download'=>0, 'query'=>0, 'create_time'=>time()]);
            $res ? $this->success('成功') : $this->error('失败');
        }
        if(!file_exists('uploads/qrcode/')){
            mkdir('uploads/qrcode/');
        }
        return $this->fetch();
    }
    //删除
    public function del()
    {
        $ids = $this->request->param('ids/a', null);
        if (empty($ids)) {
            $this->error('参数错误！');
        }
        if (!is_array($ids)) {
            $ids = array(0 => $ids);
        }
        $res = Db::name('qrcode')->whereIn('id', $ids)->delete();
        $res ? $this->success('删除成功') : $this->error('删除失败');
        $this->success('删除成功！');
    }
    public function export(){
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $list = Db::name('qrcode')->where('download', 0)->field('id,code')->order('create_time asc,id asc')->limit($param['number'])->select();
            if(empty($list)){
                $this->error('暂无未导出二维码');
            }
            $filename = 'uploads/qrcode/'.time().".zip";       
            $zip = new \ZipArchive();
            $zip->open($filename, \ZIPARCHIVE::CREATE);
            $path = 'uploads/qrcode/';
            foreach($list as $key => $value){
                $zip->addFile($path.$value['code'].'.png',$value['code'].'.png');
            }
            $zip->close();
            $res = Db::name('qrcode')->where('id','>=',$list[0]['id'])->where('id','<=',$list[count($list)-1]['id'])->update(['download'=>1]);
            $res ? $this->success('导出成功', 'http://'.$_SERVER['HTTP_HOST'].'/'.$filename) : $this->error('导出失败');
        }
        if(!file_exists('uploads/qrcode/')){
            mkdir('uploads/qrcode/');
        }
        return $this->fetch();
    }
    public function getNonceStr($length = 8) 
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";  
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {  
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
        }
        $item = Db::name('qrcode')->where('code',$str)->find();
        if(!empty($item)){
            return $this->getNonceStr($length);
        }
        return $str;
    }
    public function exportExcel(){
        $get = $this->request->get('', null, null);
        list($page, $limit, $where) = $this->buildTableParames();
        $header = [
            ['编码','code'],
            ['链接','url'],
            ['状态','download'],
            ['查询次数','query'],
            ['创建时间','create_time']
        ];
        $list = Db::name('qrcode')
            ->where($where)
            ->field('*,FROM_UNIXTIME(create_time,"%Y-%m-%d %H:%i:%s") as create_time,if(download=1,"已下载","未下载") as download')
            ->order('create_time desc,id desc')->select(); 
        
        $fileName = '防伪二维码'.time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }
}